<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 商品规格</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="query.name" @keyup.enter.native="handleSearch" placeholder="商品规格"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-select v-model="query.categoryId" placeholder="--选择类别--" filterable clearable>
                        <el-option v-for="item in selectCategory" :key="item.id" :label="item.title" :value="item.id">
                            <span :style="item.parentId == 0 ? '' : 'padding-left:10px;'">{{ item.title }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                    <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
                </el-form-item>
            </el-form>
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                row-key="id"
            >
                @selection-change="handleSelectionChange" >

                <el-table-column class-name="user2" prop="name" label="商品规格"></el-table-column>
                <el-table-column prop="categoryId" :formatter="categoryFilter"  label="所属类别" align="center"></el-table-column>
                <el-table-column prop="specValueNames" label="规格项" align="center"></el-table-column>
                <!-- <el-table-column prop="memo" label="备注" align="center"></el-table-column> -->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    background
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 15, 20, 30]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :before-close="closeDialog" :close-on-click-modal="false" title="商品规格" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" id="form" label-width="100px" :rules="rulesForm">
                <el-form-item label="商品规格" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>

                <el-form-item label="所属分类" prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="--选择类别--" filterable>
                        <el-option v-for="item in selectCategory" :key="item.id" :label="item.title" :value="item.id">
                            <span :style="item.parentId == 0 ? '' : 'padding-left:10px;'">{{ item.title }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="规格项">
                    <el-input placeholder="" v-model="tempItemValue">
                        <el-button slot="append" icon="el-icon-plus" @click="addItemValue()"></el-button>
                    </el-input>
                </el-form-item>

                <el-form-item label="">
                    <el-tag :key="tag" v-for="tag in Tags" closable :disable-transitions="false" @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                </el-form-item>

                <!-- <el-form-item label="备注" prop="memo">
                    <el-input type="textarea" :rows="2" placeholder="写点什么吧" v-model="form.memo"> </el-input>
                    <el-input type="textarea" placeholder="写点什么吧" v-model="form.memo"> </el-input>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog()">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'memberlevel_list', //去掉name则每次点击菜单，都出发created
    data() {
        return {
            query: {
                name: '',
                categoryId: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            editVisible: false,
            tempItemValue: '',
            selectCategory: [],
            pageTotal: 0,
            form: {
                id: 0,
                name: '',
                categoryId: 0,
                memo: ''
            },
            Tags: [],
            inputVisible: false,
            inputValue: '',
            loading: false,

            rulesForm: {
                name: [
                    {
                        required: true,
                        message: '请输入商品规格!',
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    created() {
        this.loading = true;
        this.getData();
        this.getCategorySelect();
    },
    methods: {
        categoryFilter(row, column) {
            var str = this.selectCategory.filter((c) => c.id == row.categoryId);
            if (str.length > 0) return str[0].title;
            else return '';
        },
        // 触发搜索按钮
        handleSearch() {
            this.query.pageIndex = 1;
            this.getData();
        },
        getData() {
            this.loading = true;
            var cid = this.query.categoryId || '';
            var categoryIds = [];
            if (cid != '') categoryIds.push(cid);
            var parmas = {
                name: this.query.name,
                categoryId: categoryIds,
                pageIndex: this.query.pageIndex,
                pageSize: this.query.pageSize
            };
            //config.gatewayUrl='http://localhost:52296';
            axios({
                url: config.gatewayUrl + '/api/product/spec/paged',
                method: 'post',
                data: parmas,
                headers: {
                    // 'Content-Type': 'multipart/form-data'
                }
            }).then((res) => {
                this.tableData = res.data.items;
                this.pageTotal = res.data.totalCount;
                this.loading = false;
            });
        },
        getCategorySelect() {
            var query = {
                title: '',
                parentId: null,
                pageIndex: 1,
                pageSize: 10000 //Number.MAX_SAFE_INTEGER
            };

            axios({
                url: config.gatewayUrl + '/api/product/cat/paged',
                method: 'post',
                data: query
            }).then((res) => {
                if (res.data && res.data.items.length > 0) {
                    this.selectCategory = res.data.items;

                    var firstCategory = res.data.items.filter(function (item) {
                        return item.parentId == 0;
                    });
                    var secondCategory = res.data.items.filter(function (item) {
                        return item.parentId > 0;
                    });

                    var st = [];

                    for (let index = 0; index < firstCategory.length; index++) {
                        st.push(firstCategory[index]);
                        var t = secondCategory.filter(function (item) {
                            return item.parentId == firstCategory[index].id;
                        });
                        st = st.concat(t);
                    }

                    this.selectCategory = st;
                }
            });
        },
        addItemValue() {
            var text = String(this.tempItemValue).trim();
            if (text != '') {
                this.Tags.push(text);
                this.tempItemValue = '';
            }
        },
        // 编辑操作
        handleEdit(index, row) {
   
            if (row) {
                this.form.id = row.id;
                this.form.name = row.name;
                this.form.categoryId = row.categoryId;
                // this.form.memo = row.memo;
                this.Tags = String(row.specValueNames).split(',');
            } else {
                this.form = { id: null, name: '', memo: '', categoryId: this.selectCategory[1].id };
            }
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit(formName) {
            var that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.Tags.length == 0) {
                        this.$message.error('至少添加一个规格项！');
                        return;
                    }
                    var dto = this.form;
                    dto.specNames = this.Tags;
            
                    axios
                        .post(config.gatewayUrl + '/api/product/spec/create', dto)
                        .then((res) => {
                            if (res.data.result == false) {
                                that.$message.error(res.data.promptMsg);
                                console.log(res);
                            } else {
                                that.$refs.form.clearValidate();
                                //that.editVisible = false;
                                that.closeDialog();
                                that.$message.success(`保存成功!`);
                                that.getData();
                            }
                        })
                        .catch((error) => {
                            console.log(error); //  错误处理 相当于error
                        });
                    that.$refs.form.clearValidate();
                } else {
                    return false;
                }
            });
        },

        closeDialog() {
            var that = this;
            //this.$refs.form.resetFields();
            this.form = { id: null, name: '', categoryId: this.selectCategory[0].value };
            console.log(this.form);
            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);
            this.Tags = [];
            this.editVisible = false;
        },
        handleClose(tag) {
            this.Tags.splice(this.Tags.indexOf(tag), 1);
            //console.log(this.Tags);
        },

        // 分页导航
        handlePageChange(val) {
            //跳转到
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        handleSizeChange(val) {
            //改变页码
            this.query.pageSize = val;
            this.getData();
        },
        handleCurrentChange(val) {
            //下一页console.log(`当前页: ${val}`);
            this.query.pageIndex = val;
            this.getData();
        }
    },
    watch: {}
};
</script>
<style scoped>
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>